﻿Imports TBCC.UserManage
Imports iTextSharp
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO
Imports System.Text
Imports System.Xml
Imports iTextSharp.text.html
Public Class HDDocViewForm

    Private _IntevalType As String = "3"
    Private _IntevalValue As Integer = 1
    Private _LimitStr As String = ""

    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        If sender.Text = "取消" Then
            sender.Text = "正在取消..."
            sender.Enabled = False
            bwSearch.CancelAsync()
            Exit Sub
        End If

        If CheckValidate() = False Then
            Exit Sub
        End If

        Me.DataGridView1.DataSource = Nothing
        Me.DataGridView1.Columns.Clear()
        Me.DataGridView2.Rows.Clear()
        Me.DataGridView2.Columns.Clear()

        'Me.DataGridView1.Cursor = Cursors.WaitCursor
        Me.cboRef.Enabled = False
        'Me.btnRefresh.Enabled = False
        Me.btnRefresh.Text = "取消"
        Me.btnPrint.Enabled = False
        Me.btnExport.Enabled = False
        Me.btnPDFExport.Enabled = False
        ' Me.BtnLimit.Enabled = False
        Me.dtpFrom.Enabled = False
        Me.dtpTo.Enabled = False
        Me.pnlSearch.Visible = True
        Logger.Write(User.Instance.uID, User.Instance.uName, "查看历史数据", tbccLogOperateType.View)


        Me.bwSearch.RunWorkerAsync(New Object() {cboRef.SelectedItem})
        'RefreshData()
        'Me.dtpFrom.Enabled = True
        'Me.dtpTo.Enabled = True
        'Me.btnRefresh.Enabled = True
        'Me.DataGridView1.Cursor = Cursors.Default

    End Sub

    Dim tArray As New ArrayList()
    Dim hArray As New ArrayList()
    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <remarks></remarks>
    Private Function RefreshData(ByVal cbo_rti As RefTypeItem) As Object()
        Dim strSql As String
        'Dim m_index As Integer
        'Dim cbo_rti As RefTypeItem = CType(cboRef.SelectedItem, RefTypeItem)
        Dim apts As AiPortTypeService = New AiPortTypeService(cbo_rti)
        Dim ret() As Object = Nothing
        Dim proIndex As Integer
        'Dim tArray As New ArrayList()
        'Dim hArray As New ArrayList()
        Dim dss As New DataSet("dss1")
        Dim dss_table As DataTable = dss.Tables.Add("hd")
        dss_table.Columns.Add("num", GetType(Object))
        dss_table.Columns.Add("hDate", GetType(DateTime))
        tArray.Clear()
        hArray.Clear()
        Dim devtype As Integer
        devtype = DevTypeService.GetdevType(cbo_rti.ProjectID, cbo_rti.NetId)

        '时间间隔数据
        Dim iSeconds As Integer = HIST_SAVE_INTERVAL_TIME

        Select Case _IntevalType 'Me.cboIntevalType.Text.Trim()
            Case "1"
                iSeconds = _IntevalValue 'CInt(Me.cboSecond.Text)

            Case "2"
                iSeconds = _IntevalValue * 60 'Me.nudMinute.Value * 60

            Case "3"
                iSeconds = _IntevalValue * 3600 'Me.nudHour.Value * 3600

            Case Else
                iSeconds = _IntevalValue * 3600
        End Select

        strSql = String.Format("select count(distinct hDate) num, hDate")


        '添加AI列标题
        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                Dim columnName As String = "AI" & Trim(apti.PortNo.ToString)

                strSql &= String.Format(",{0}", columnName)
                dss_table.Columns.Add(columnName, GetType(String))
                Select Case devtype
                    Case 1
                        If apti.PortNo <= 9 Then
                            tArray.Add(columnName)
                        Else
                            hArray.Add(columnName)
                        End If
                    Case 16
                        If apti.PortNo <= 16 Then
                            tArray.Add(columnName)
                        Else
                            hArray.Add(columnName)
                        End If

                End Select

            End If
        Next


        'If is_firstrun = True Then '当前冷库没有配置AI
        '    msg.Show("指定冷库尚未配置数据端口")
        'End If

        'strSql &= String.Format(" From tbccHDData_{0}_{1} Where hDate>='{2}' and hDate<='{3}' order by hDate", Trim(cbo_rti.ProjectID).Replace("-", "_"), cbo_rti.NetId, UtilityClass.GetDateString(Me.dtpFrom.Value), UtilityClass.GetDateString(Me.dtpTo.Value))

        strSql &= String.Format(" From tbccHDData_{0}_{1} where hdate between '{2}' and '{3}' and ((HOUR(hdate)*3600+ MINUTE(hdate)*60+SECOND(hdate))- (HOUR('{2}')*3600+ MINUTE('{2}')*60+SECOND('{2}'))) % {4} =0 {5} group by hDate order by hDate", Trim(cbo_rti.ProjectID).Replace("-", "_"), cbo_rti.NetId, UtilityClass.GetDateString(Me.dtpFrom.Value), UtilityClass.GetDateString(Me.dtpTo.Value), iSeconds, _LimitStr)

        Dim ds As DataSet = Nothing
        Dim tmpObj As Object

        Try

            Select Case MainForm.readConfig("SystemType")
                Case 2
                    ds = SqlHelper1.ExecuteDataset(strSql, Nothing)
                Case Else
                    ds = SqlHelper.ExecuteDataset(strSql, Nothing)
            End Select

            If Me.bwSearch.CancellationPending Then Return Nothing '取消查询


            '时间间隔数据
            'Dim iSeconds As Integer = HIST_SAVE_INTERVAL_TIME

            'Select Case _IntevalType 'Me.cboIntevalType.Text.Trim()
            '    Case "1"
            '        iSeconds = _IntevalValue 'CInt(Me.cboSecond.Text)

            '    Case "2"
            '        iSeconds = _IntevalValue * 60 'Me.nudMinute.Value * 60

            '    Case "3"
            '        iSeconds = _IntevalValue * 3600 'Me.nudHour.Value * 3600

            '    Case Else
            '        iSeconds = _IntevalValue * 3600
            'End Select

            Dim dtStart As DateTime
            dtStart = AdjustDateTime(Me.dtpFrom.Value)

            proIndex = 0
            For Each r As DataRow In ds.Tables(0).Rows
                dss_table.Rows.Add(r.ItemArray)
            Next
            Dim dtTmp As DateTime
            'For Each r As DataRow In ds.Tables(0).Rows
            For Each r As DataRow In dss_table.Rows
                If Me.bwSearch.CancellationPending Then Return Nothing '取消查询
                tmpObj = r("hdate")
                dtTmp = IIf(IsDBNull(tmpObj) = False, tmpObj, DateTime.MinValue)
                'If dtTmp.Subtract(dtStart).TotalSeconds Mod iSeconds <> 0 Then
                '    r.Delete()
                'End If
                proIndex += 1
                'Me.bwSearch.ReportProgress((proIndex / ds.Tables(0).Rows.Count) * 100) '报告进度
                ReportProgress((proIndex / ds.Tables(0).Rows.Count) * 100)
            Next

            dss.AcceptChanges()


            If dss.Tables(0).Rows.Count <= 0 Then
                'Me.DataGridView1.Columns.Clear()
                'Me.DataGridView2.Columns.Clear()
                'Me.btnPrint.Enabled = False
                'msg.Show("指定时间范围没有数据,请重新设置时间范围")
                dss.Clear() : dss.Dispose() : dss = Nothing
                Return Nothing
                'Else
                '    Me.btnPrint.Enabled = True
            End If

            If ds.Tables(0).Rows.Count <= 0 Then
                ds.Clear() : ds.Dispose() : ds = Nothing
                Return Nothing

            End If

            '添加DataSet列
            'Dim table As DataTable = ds.Tables(0)
            Dim table As DataTable = dss_table
            If tArray.Count > 0 Then 'array.count > 0
                table.Columns.Add("hTMax")
                table.Columns.Add("hTMin")
                table.Columns.Add("hTAvg")
            End If
            If hArray.Count > 0 Then 'array.count > 0
                table.Columns.Add("hHMax")
                table.Columns.Add("hHMin")
                table.Columns.Add("hHAvg")
            End If

            dss.AcceptChanges()


            'min/max/avg
            Dim IsRecNotUsed As Boolean
            Dim hMin, hMax, hAvg As Object
            Dim hSum As Object
            Dim vRow As Integer = 0
            Dim vTRow As Integer = 0
            Dim vRRow As Integer = 0
            Dim vValidRow As Integer = 0
            Dim vLen As Integer = tArray.Count + hArray.Count
            'If tArray.Count > 1 Then vLen += 3 '去处统计中T的3列; 2008.10.31
            'If hArray.Count > 1 Then vLen += 3 '去处统计中H的3列; 2008.10.31
            Dim vMin(vLen - 1), vMax(vLen - 1), vAvg(vLen - 1) As Object
            Dim vSum(vLen - 1) As Decimal
            Dim vCount(vLen - 1) As Integer
            For i As Integer = 0 To vLen - 1
                vMin(i) = Double.MaxValue : vMax(i) = Double.MinValue : vAvg(i) = 0 : vSum(i) = 0 : vCount(i) = 0
            Next
            For Each r As DataRow In dss_table.Rows
                If Me.bwSearch.CancellationPending Then Return Nothing '取消查询
                '计算温度水平/垂直min/max/avg值
                If tArray.Count > 0 Then 'array.count > 0
                    hMin = Double.MaxValue : hMax = Double.MinValue : hAvg = 0 : hSum = 0

                    IsRecNotUsed = False
                    For i As Integer = 0 To tArray.Count - 1
                        tmpObj = r(tArray(i))
                        'Dim value As Double

                        If UtilityClass.IsNotNullEmpty(tmpObj) = True Then
                            If tmpObj = INVALID_DATA Then
                                'IsRecNotUsed = True
                                'r.Delete()
                                'Exit For
                                r(tArray(i)) = "未激活"
                            Else

                                If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                    If (tmpObj.ToString.Length - 1 - tmpObj.ToString.LastIndexOf(".")) > 1 Then
                                        tmpObj = tmpObj.ToString.Remove((tmpObj.ToString.Length - 1), 1)
                                        If tmpObj.ToString.Chars(tmpObj.ToString.Length - 1) = "0" Then
                                            tmpObj = tmpObj.ToString.Remove((tmpObj.ToString.Length - 2), 2)

                                        End If
                                        r(tArray(i)) = tmpObj

                                    End If

                                End If
                               
                                
                                'Select Case MainForm.readConfig("SystemType")
                                '    Case 0, 1
                                If IIf(KeyValuePairClass.GetValue1("ServerSysType").Equals("1"), True, False) Then

                                    Select Case cbo_rti.RefType
                                        Case 1   '冷库
                                            If tmpObj > g_TemType1max Then

                                                If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                                    r(tArray(i)) = g_TemType1max - 1 + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿
                                                Else
                                                    r(tArray(i)) = g_TemType1max

                                                End If



                                            ElseIf tmpObj < g_TemType1min Then

                                                If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                                    r(tArray(i)) = g_TemType1min + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿
                                                Else
                                                    r(tArray(i)) = g_TemType1min

                                                End If


                                            End If
                                        Case 2  '阴凉库
                                            If tmpObj > g_TemType2max Then
                                                If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                                    r(tArray(i)) = g_TemType2max - 1 + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿

                                                Else
                                                    r(tArray(i)) = g_TemType2max

                                                End If


                                            ElseIf tmpObj < g_TemType2min Then
                                                If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                                    r(tArray(i)) = g_TemType2min + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿
                                                Else
                                                    r(tArray(i)) = g_TemType2min

                                                End If

                                            End If
                                        Case 3  '冰库
                                            If tmpObj > g_TemType3max Then
                                                If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                                    r(tArray(i)) = g_TemType3max - 1 + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿
                                                Else
                                                    r(tArray(i)) = g_TemType3max

                                                End If


                                            ElseIf tmpObj < g_TemType3min Then
                                                If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                                    r(tArray(i)) = g_TemType3min + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿
                                                Else
                                                    r(tArray(i)) = g_TemType3min

                                                End If

                                            End If
                                        Case 4  '低温库
                                            If tmpObj > g_TemType4max Then
                                                If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                                    r(tArray(i)) = g_TemType4max - 1 + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf("."))
                                                Else
                                                    r(tArray(i)) = g_TemType4max
                                                End If


                                            ElseIf tmpObj < g_TemType4min Then
                                                If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                                    r(tArray(i)) = g_TemType4min + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf("."))
                                                Else
                                                    r(tArray(i)) = g_TemType4min

                                                End If

                                            End If
                                        Case Else


                                    End Select

                                End If
                                '    Case 2  '类型为2修改所有数据为合格数据
                                '        Select Case MainForm.readConfig("Type")
                                '            Case 0
                                '                Select Case cbo_rti.RefType
                                '                    Case 1   '冷库
                                '                        If tmpObj > g_TemType1max Then

                                '                            If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                '                                r(tArray(i)) = g_TemType1max - 1 + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿
                                '                            Else
                                '                                r(tArray(i)) = g_TemType1max

                                '                            End If



                                '                        ElseIf tmpObj < g_TemType1min Then

                                '                            If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                '                                r(tArray(i)) = g_TemType1min + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿
                                '                            Else
                                '                                r(tArray(i)) = g_TemType1min

                                '                            End If


                                '                        End If
                                '                    Case 2  '阴凉库
                                '                        If tmpObj > g_TemType2max Then
                                '                            If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                '                                r(tArray(i)) = g_TemType2max - 1 + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿

                                '                            Else
                                '                                r(tArray(i)) = g_TemType2max

                                '                            End If


                                '                        ElseIf tmpObj < g_TemType2min Then
                                '                            If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                '                                r(tArray(i)) = g_TemType2min + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿
                                '                            Else
                                '                                r(tArray(i)) = g_TemType2min

                                '                            End If

                                '                        End If
                                '                    Case 3  '冰库
                                '                        If tmpObj > g_TemType3max Then
                                '                            If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                '                                r(tArray(i)) = g_TemType3max - 1 + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿
                                '                            Else
                                '                                r(tArray(i)) = g_TemType3max

                                '                            End If


                                '                        ElseIf tmpObj < g_TemType3min Then
                                '                            If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                '                                r(tArray(i)) = g_TemType3min + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿
                                '                            Else
                                '                                r(tArray(i)) = g_TemType3min

                                '                            End If

                                '                        End If
                                '                    Case 4  '低温库
                                '                        If tmpObj > g_TemType4max Then
                                '                            If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                '                                r(tArray(i)) = g_TemType4max - 1 + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf("."))
                                '                            Else
                                '                                r(tArray(i)) = g_TemType4max
                                '                            End If


                                '                        ElseIf tmpObj < g_TemType4min Then
                                '                            If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                '                                r(tArray(i)) = g_TemType4min + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf("."))
                                '                            Else
                                '                                r(tArray(i)) = g_TemType4min

                                '                            End If

                                '                        End If
                                '                    Case Else


                                '                End Select
                                '            Case Else

                                '        End Select
                                'End Select

                            End If
                        End If
                    Next

                    If IsRecNotUsed = True Then
                        vRow += 1
                        ReportProgress((vRow / ds.Tables(0).Rows.Count) * 100)
                        ' Continue For
                    End If

                    For i As Integer = 0 To tArray.Count - 1


                        tmpObj = r(tArray(i))
                        Dim value As Double

                        If tmpObj.ToString = "未激活" Then
                            value = 0
                            IsRecNotUsed = True
                            r(tArray(i)) = "未激活"
                            'hMin = "--"
                            'hMax = "--"
                            'hSum = "--"
                            Continue For
                        Else
                            If UtilityClass.IsNotNullEmpty(tmpObj) = True Then
                                value = tmpObj.ToString
                                value = Math.Round(value, 1)
                                vTRow += 1
                            Else
                                value = 0
                                r(tArray(i)) = Math.Round(value, 1)

                            End If

                        End If



                        '水平
                        If value < hMin Then hMin = value
                        If value > hMax Then hMax = value
                        hSum += value

                        If hMin = Double.MaxValue Then
                            hMin = "--"
                            hMax = "--"
                            hSum = "--"

                        End If

                        '垂直
                        If value < vMin(i) Then vMin(i) = value
                        If value > vMax(i) Then vMax(i) = value
                        vSum(i) += value
                        vCount(i) += 1
                    Next

                    If hMin = Double.MaxValue Then
                        hMin = "--"
                        hMax = "--"
                        hSum = "--"

                    End If
                    If hSum Is "--" Then
                        r("hTMax") = "--"
                        r("hTMin") = "--"
                        r("hTAvg") = "--"

                    Else
                        hAvg = hSum / vTRow
                        vTRow = 0
                        r("hTMax") = hMax
                        r("hTMin") = hMin
                        r("hTAvg") = Math.Round(hAvg, 1)
                    End If

                End If

                '计算湿度水平/垂直min/max/avg值
                If hArray.Count > 0 Then 'array.count > 0
                    hMin = Double.MaxValue : hMax = Double.MinValue : hAvg = 0 : hSum = 0
                    IsRecNotUsed = False
                    For i As Integer = 0 To hArray.Count - 1
                        tmpObj = r(hArray(i))
                        'Dim value As Double

                        If UtilityClass.IsNotNullEmpty(tmpObj) = True Then
                            If tmpObj = INVALID_DATA Then
                                ' IsRecNotUsed = True
                                'r.Delete()
                                'Exit For
                                r(hArray(i)) = "未激活"
                            Else '修改合格数据



                                If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                    If (tmpObj.ToString.Length - 1 - tmpObj.ToString.LastIndexOf(".")) > 1 Then
                                        tmpObj = tmpObj.ToString.Remove((tmpObj.ToString.Length - 1), 1)
                                        If tmpObj.ToString.Chars(tmpObj.ToString.Length - 1) = "0" Then
                                            tmpObj = tmpObj.ToString.Remove((tmpObj.ToString.Length - 2), 2)

                                        End If
                                        r(hArray(i)) = tmpObj

                                    End If

                                End If
                               
                                If IIf(KeyValuePairClass.GetValue1("ServerSysType").Equals("1"), True, False) Then
                                    If tmpObj > g_HumType1max Then
                                        If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                            r(hArray(i)) = g_HumType1max - 1 + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿'+数据小数点儿
                                        Else
                                            r(hArray(i)) = g_HumType1max

                                        End If



                                    ElseIf tmpObj < g_HumType1min Then

                                        If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                            r(hArray(i)) = g_HumType1min + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿'+数据小数点儿
                                        Else
                                            r(hArray(i)) = g_HumType1min

                                        End If



                                    End If

                                End If
                                '    Case 2  '类型为2修改所有数据为合格数据
                                'Select Case MainForm.readConfig("Type")
                                '    Case 0
                                'If tmpObj > g_HumType1max Then
                                '    If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                '        r(hArray(i)) = g_HumType1max - 1 + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿'+数据小数点儿
                                '    Else
                                '        r(hArray(i)) = g_HumType1max

                                '    End If



                                'ElseIf tmpObj < g_HumType1min Then

                                '    If tmpObj.ToString.LastIndexOf(".") >= 0 Then
                                '        r(hArray(i)) = g_HumType1min + tmpObj.ToString.Remove(0, tmpObj.ToString.LastIndexOf(".")) '+数据小数点儿'+数据小数点儿
                                '    Else
                                '        r(hArray(i)) = g_HumType1min

                                '    End If



                                'End If
                                '    Case Else

                                'End Select
                                ' End Select

                            End If
                        End If
                    Next

                    If IsRecNotUsed = True Then
                        vRow += 1
                        ReportProgress((vRow / ds.Tables(0).Rows.Count) * 100)
                        ' Continue For
                    End If


                    For i As Integer = 0 To hArray.Count - 1
                        tmpObj = r(hArray(i))
                        Dim value As Double

                        If tmpObj.ToString = "未激活" Then
                            value = 0
                            IsRecNotUsed = True
                            r(hArray(i)) = "未激活"
                            'hMin = "--"
                            'hMax = "--"
                            'hSum = "--"

                            Continue For
                        Else
                            If UtilityClass.IsNotNullEmpty(tmpObj) = True Then
                                value = tmpObj.ToString
                                value = Math.Round(value, 1)
                                vRRow += 1
                            Else
                                value = 0
                                r(hArray(i)) = Math.Round(value, 1)
                            End If

                        End If


                        '水平
                        If value < hMin Then hMin = value
                        If value > hMax Then hMax = value
                        hSum += value

                        If hMin = Double.MaxValue Then
                            hMin = "--"
                            hMax = "--"
                            hSum = "--"

                        End If

                        '垂直
                        Dim j As Integer = tArray.Count + i
                        'If r(j + 1) = "未激活" Then
                        '    r(j + 1) = 0
                        'End If
                        value = r(j + 2) 'i + 1跳过时间列

                        If value < vMin(j) Then vMin(j) = value
                        If value > vMax(j) Then vMax(j) = value
                        vSum(j) += value
                        vCount(j) += 1
                    Next

                    If hMin = Double.MaxValue Then
                        hMin = "--"
                        hMax = "--"
                        hSum = "--"

                    End If

                    If hSum Is "--" Then
                        r("hHMax") = "--"
                        r("hHMin") = "--"
                        r("hHAvg") = "--"

                    Else
                        hAvg = hSum / vRRow
                        vRRow = 0
                        r("hHMax") = hMax
                        r("hHMin") = hMin
                        r("hHAvg") = Math.Round(hAvg, 1)
                    End If
                End If

                ''计算温度垂直min/max/avg值
                'If tArray.Count > 0 Then
                '    For i As Integer = 0 To tArray.Count - 1
                '        Dim value As Double = r(tArray(i))
                '        If value < vMin(i) Then vMin(i) = value
                '        If value > vMax(i) Then vMax(i) = value
                '        vSum(i) += value
                '    Next
                'End If

                ''计算湿度垂直min/max/avg值
                'If hArray.Count > 0 Then
                '    For i As Integer = tArray.Count To vLen - 1
                '        Dim value As Double = r(i + 1) 'i + 1跳过时间列
                '        If value < vMin(i) Then vMin(i) = value
                '        If value > vMax(i) Then vMax(i) = value
                '        vSum(i) += value
                '    Next
                'End If

                If IsRecNotUsed = False Then
                    vValidRow += 1
                End If

                vRow += 1

                'Me.bwSearch.ReportProgress((vRow / ds.Tables(0).Rows.Count) * 100) '报告进度
                ReportProgress((vRow / ds.Tables(0).Rows.Count) * 100)
            Next


            For i As Integer = 0 To vLen - 1
                'If vValidRow <> 0 Then
                '    vAvg(i) = vSum(i) / vValidRow

                'End If
                If vCount(i) <> 0 Then
                    vAvg(i) = vSum(i) / vCount(i)

                End If

            Next

            'Dim row As DataRow
            'row = table.NewRow()
            'row(0) = "最大值"
            'For i As Integer = 0 To vLen - 1
            '    row(i + 1) = vMax(i)
            'Next
            'table.Rows.Add(row)

            'row = table.NewRow()
            'row(0) = "最小值"
            'For i As Integer = 0 To vLen - 1
            '    row(i + 1) = vMin(i)
            'Next
            'table.Rows.Add(row)

            'row = table.NewRow()
            'row(0) = "平均值"
            'For i As Integer = 0 To vLen - 1
            '    row(i + 1) = Math.Round(vSum(i) / vRow, 4)
            'Next
            'table.Rows.Add(row)

            dss.AcceptChanges()

            For i As Integer = 0 To vMax.Length - 1
                If vMax(i) = Double.MinValue Then
                    vMax(i) = "--"
                    vMin(i) = "--"
                    vAvg(i) = "--"
                End If
            Next

            'For j As Integer = 0 To vMax.Length - 1
            '    If vMin(j) = Double.MaxValue Then
            '        vMin(j) = "--"
            '    End If
            'Next


            ret = New Object() {dss, vMax, vMin, vAvg, vLen}


        Catch ex As Exception
            'Me.DataGridView1.Columns.Clear()
            'Me.DataGridView2.Columns.Clear()
            'Me.btnPrint.Enabled = False
            'msg.Show("指定时间范围没有数据,请重新设置时间范围")
            If ds IsNot Nothing Then
                ds.Clear() : ds.Dispose() : ds = Nothing
            End If
            If dss IsNot Nothing Then
                dss.Clear() : dss.Dispose() : dss = Nothing
            End If
        End Try

        Return ret
    End Function

    ''' <summary>
    ''' 检查时间范围是否合法
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckValidate() As Boolean
        If Me.dtpTo.Value < Me.dtpFrom.Value Then
            msg.ShowWarning("起始时间不能大于终止时间。")
            Me.dtpFrom.Focus()
            Return False
        End If

        '限制查询的历史记录数量
        Dim ratio As Integer = 1
        Select Case _IntevalType
            Case "1"
                ratio = 1
            Case "2"
                ratio = 6

            Case "3"
                ratio = 360
            Case Else
                Return False
        End Select

        If Me.dtpTo.Value > Me.dtpFrom.Value.AddDays(7 * ratio) Then
            msg.ShowWarning(String.Format("查询的时间间隔不能超过{0}天", 7 * ratio))
            Me.dtpFrom.Focus()
            Return False
        End If

        Return True
    End Function

    Private Function AdjustDateTime(ByVal dt As DateTime) As DateTime
        Return dt.AddSeconds(-dt.Second Mod HIST_SAVE_INTERVAL_TIME)
    End Function

    Private Sub HDDocViewForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.DataGridView1.AutoGenerateColumns = False

        'Me.cboIntevalType.SelectedIndex = 2
        Me.cboRef.SelectedIndex = -1

        Dim dt As DateTime = UtilityClass.GetDateString(Now)
        dtpTo.Value = dt
        dtpFrom.Value = dt.ToLongDateString()
        'dtpFrom.Value = dtpFrom.Value.AddMonths(-1)
        dtpFrom.Value = dtpFrom.Value.AddDays(-1)
        LoadRef()

    End Sub

    Private Sub LoadRef()
        Dim rts As RefTypeService = New RefTypeService(MainForm.pi)

        For Each rti As RefTypeItem In rts.GeRefGroupList()
            cboRef.Items.Add(rti)
        Next

        '获取时间间隔参数; 2008.10.31
        Dim it, iv As String
        it = KeyValuePairClass.GetValue(MainForm.pi.ProjectID, "DocViewType")
        iv = KeyValuePairClass.GetValue(MainForm.pi.ProjectID, "DocViewValue")
        If it.Length > 0 Then _IntevalType = it
        If iv.Length > 0 Then _IntevalValue = CInt(iv)

        cboRef.SelectedIndex = -1
        btnRefresh.Enabled = False
        btnPrint.Enabled = False
        ' CheckUserRight(MainForm)
        btnExport.Enabled = False
        Me.btnPDFExport.Enabled = False
        Me.BtnLimit.Enabled = False


    End Sub
    ''' <summary>
    ''' 获取时间间隔
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub GetSpace()

        '获取时间间隔参数; 2008.10.31
        Dim it, iv As String
        it = KeyValuePairClass.GetValue(MainForm.pi.ProjectID, "DocViewType")
        iv = KeyValuePairClass.GetValue(MainForm.pi.ProjectID, "DocViewValue")
        If it.Length > 0 Then _IntevalType = it
        If iv.Length > 0 Then _IntevalValue = CInt(iv)


    End Sub
    Private Sub CheckUserRight(ByVal frm As MainForm)
        Dim gp As System.Security.Principal.GenericPrincipal
        gp = My.User.CurrentPrincipal

        If gp.IsInRole(RoleClass.GetRolename(RoleType.HighLevel)) Then
            btnExport.Visible = True
            Me.btnPDFExport.Enabled = True

        Else
            btnExport.Visible = False
            Me.btnPDFExport.Enabled = False

        End If
    End Sub

    Dim cols(100) As String
    Dim headers(100) As String

    Private Sub Print()
        ' Dim k As Integer
        Dim dt As DataTable
        dt = CType(Me.DataGridView1.DataSource, DataTable)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            msg.Show("没有数据")
            Exit Sub
        End If


        For i As Integer = 0 To dt.Rows.Count - 1
            Dim r As DataRow = dt.Rows(i)
            If r(2).ToString = "未激活" Then
                r.Delete()
                Continue For
            End If
        Next

        dt.AcceptChanges()

        Dim objExcel As New Excel.Application

        Dim wb As Excel.Workbook = objExcel.Workbooks.Add()

        '  excel.Application.Workbooks.Add(True)
        'objExcel.Visible = True

        ReDim Preserve cols(100)


        Dim index As Integer = 0
        cols(index) = "序号"
        headers(index) = "序号"
        For i As Integer = 0 To Me.DataGridView1.Columns.Count - 1
            'For i As Integer = 0 To dt.Rows.Count - 1




            If Me.DataGridView1.Columns(i).Visible Then
                index += 1
                cols(index) = Me.DataGridView1.Columns(i).DataPropertyName
                headers(index) = Me.DataGridView1.Columns(i).HeaderText
            End If
        Next

        ReDim Preserve cols(index)

        'Dim bRow As Integer = dt.Rows.Count
        ''Dim values(,) As Object
        Dim values(dt.Rows.Count, cols.Length + 1) As Object 'cols.Length + 1:时间为2列
        'If bRow Mod 32 <> 0 Then
        '    Dim ba As Integer = bRow \ 32
        '    bRow = (ba + 1) * 32
        '    'ReDim values(bRow, cols.Length)
        'Else
        '    'ReDim values(bRow, cols.Length)
        'End If
        'For i As Integer = 0 To values.GetLength(0) - 1
        '    For j As Integer = 0 To values.GetLength(1) - 1
        '        values(i, j) = Strings.Space(1)
        '    Next
        'Next

        For j As Integer = 0 To cols.Length
            If j > 1 Then
                values(0, j + 1) = headers(j) 'j+1:跳过时间2列(共2列)
            Else
                values(0, j) = headers(j)
            End If
        Next

        '
        For i As Integer = 0 To dt.Rows.Count - 1
            Dim r As DataRow = dt.Rows(i)
            'If r(2) = "未激活" Then
            '    ' r.Delete()
            '    Continue For
            'End If

            values(i + 1, 0) = i + 1
            For j As Integer = 1 To cols.Length - 1 '跳过GridView第一列


                If j > 1 Then
                    values(i + 1, j + 1) = r(cols(j)) 'j+1:跳过时间2列(共2列)
                Else
                    values(i + 1, j) = r(cols(j))
                End If
            Next
        Next

        'Get stat values
        Dim statValues(3, Me.DataGridView1.Columns.Count) As Object
        For i As Integer = 0 To statValues.GetLength(0) - 1 'init values
            For j As Integer = 0 To statValues.GetLength(1) - 1
                'If statValues(i, j) = "未激活" Then
                '    Continue For
                'Else
                statValues(i, j) = String.Empty

                ' End If

            Next
        Next
        For i As Integer = 0 To Me.DataGridView2.Rows.Count - 1 '3
            Dim r As DataGridViewRow = Me.DataGridView2.Rows(i)
            For j As Integer = 0 To Me.DataGridView2.Columns.Count - 1

                statValues(i, j) = r.Cells(j).Value



            Next j
        Next i

        Dim pwd As String = System.Guid.NewGuid().ToString()
        Try
            'objExcel.Visible = True
            'objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, cols.Length)).Value = values
            'objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(bRow, cols.Length)).Value = values

            '设置格式
            objExcel.Columns("A:AA").Select()
            objExcel.Selection.HorizontalAlignment = Excel.Constants.xlCenter
            objExcel.Selection.Font.Size = 10
            objExcel.Selection.ColumnWidth = 10

            '序号
            objExcel.Range("A1", "A" & (dt.Rows.Count + 1)).ColumnWidth = 5
            'objExcel.Range("A1", "A" & (dt.Rows.Count + 1)).RowHeight = 20

            '监控时间
            'objExcel.Range("B1", objExcel.Cells(dt.Rows.Count + 1, 2)).Insert(Excel.XlInsertShiftDirection.xlShiftToRight) '插入合并列
            objExcel.Range("B1", objExcel.Cells(dt.Rows.Count + 1, 3)).ColumnWidth = 9
            objExcel.Range("B1", objExcel.Cells(dt.Rows.Count + 1, 3)).NumberFormatLocal = "yyyy-mm-dd hh:mm:ss"

            Dim totalIndex As Integer = 4 + tArray.Count + hArray.Count
            '设置温湿度列宽; 2008.10.31
            objExcel.Range(objExcel.Cells(1, 4), objExcel.Cells(dt.Rows.Count + 1, totalIndex)).ColumnWidth = 6
            objExcel.Range(objExcel.Cells(1, 4), objExcel.Cells(dt.Rows.Count + 1, totalIndex)).NumberFormatLocal = "0.00"

            '设置温湿度统计列宽; 2008.10.31
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Rows.Count + 1, 26)).ColumnWidth = 8
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Rows.Count + 1, 26)).NumberFormatLocal = "0.00"
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Rows.Count + 1, totalIndex - 1 + IIf(tArray.Count > 0, 3, 0) + IIf(hArray.Count > 0, 3, 0))).Interior.Color = RGB(255, 221, 221) 'array.count > 0

            'Dim pageRow As Integer = 27 '不包括统计的3行; 2008.10.31
            Dim statRow As Integer = 3
            Dim totalCount As Integer = Math.Ceiling(dt.Rows.Count / 30) * 30 - statRow
            If totalCount < dt.Rows.Count Then
                totalCount += statRow
            End If
            '合并单元格
            Dim range As Excel.Range
            range = objExcel.Range(objExcel.Cells(1, 2), objExcel.Cells(totalCount + 1, 3)) '合并日期单元格(dt.Rows.Count); 2008.10.31
            range.Merge(True)
            'For i As Integer = 1 To totalCount + 1
            '    range = objExcel.Range(objExcel.Cells(1, 2), objExcel.Cells(totalCount + 1, 3))
            '    range.Merge(True)
            'Next
            '合并统计单元格
            range = objExcel.Range(objExcel.Cells(totalCount + 2, 1), objExcel.Cells(totalCount + 4, 2)) '2008.10.31
            'range = objExcel.Range(objExcel.Cells(bRow - 2, 1), objExcel.Cells(bRow, 2))
            range.Merge()
            range.Value2 = "统计"
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
            range.Font.Size = 20

            'cols.Length + 1:时间为2列
            objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, cols.Length + 1)).Value2 = values

            '添加统计信息
            Dim statRange As Excel.Range
            statRange = objExcel.Range(objExcel.Cells(totalCount + 2, 3), objExcel.Cells(totalCount + 4, cols.Length + 1)) '2008.10.31
            'statRange = objExcel.Range(objExcel.Cells(bRow - 2, 3), objExcel.Cells(bRow, cols.Length + 1))
            statRange.Value2 = statValues
            'statRange.Interior.Color = RGB(221, 221, 221)
            'statRange.Interior.Pattern = 4
            'objExcel.Cells(dt.Rows.Count + 2, 1).Interior.Color = RGB(221, 221, 221)
            'objExcel.Cells(dt.Rows.Count + 2, 1).Interior.Pattern = 4

            '设置边框
            range = objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(totalCount + 4, cols.Length + 1))
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlContinuous

            '设置保护
            Try
                objExcel.ActiveSheet.Protect(pwd, _
                            AllowFormattingCells:=False, _
                            AllowFormattingColumns:=False, _
                            AllowFormattingRows:=False, _
                            AllowInsertingColumns:=False, _
                            AllowInsertingRows:=False, _
                            AllowInsertingHyperlinks:=False, _
                            AllowDeletingColumns:=False, _
                            AllowDeletingRows:=False _
                )
            Catch ex As Exception
                objExcel.ActiveSheet.Protect(pwd)
            End Try

            '温湿度值
            Dim ws As Excel.Worksheet = objExcel.ActiveSheet
            With ws.PageSetup
                '.LeftHeader = "&G" & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                .LeftHeader = vbCr & vbCr & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                .CenterHeader = String.Format("&""宋体,加粗""&28 {0}温/湿度查询 ", Me.cboRef.Text)
                .RightHeader = vbCr & vbCr & vbCr & "共&N页 第&P页"
                .LeftFooter = "养护员："
                .CenterFooter = ""
                .RightFooter = "打印日期：&D &T"
                .LeftMargin = objExcel.Application.InchesToPoints(0.6)
                .RightMargin = objExcel.Application.InchesToPoints(0.4)
                .TopMargin = objExcel.Application.InchesToPoints(1.08)
                .BottomMargin = objExcel.Application.InchesToPoints(0.68)
                .HeaderMargin = objExcel.Application.InchesToPoints(0.22)
                .FooterMargin = objExcel.Application.InchesToPoints(0.5)
                .PrintHeadings = False
                .PrintGridlines = True
                '.PrintComments = objExcel.xlPrintNoComments
                ''.PrintQuality = 300
                .CenterHorizontally = False
                .CenterVertically = False
                '.Orientation = objExcel.xlPortrait
                .Draft = False
                '.PaperSize = Excel.XlPaperSize.xlPaperA4
                .Orientation = Excel.XlPageOrientation.xlLandscape '横向打印
                '.FirstPageNumber = objExcel.xlAutomatic
                '.Order = objExcel.xlDownThenOver
                '.BlackAndWhite = False
                .Zoom = 100
                '.PrintErrors = objExcel.xlPrintErrorsDisplayed

                '.PrintArea = "A1:U" & bRow
                .FitToPagesWide = 1
                .FitToPagesTall = 1
                .PrintTitleRows = "$1:$1"


                '去掉打印泰陵图标
                'Try

                '    With .LeftHeaderPicture
                '        .Filename = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\ClientLogo.jpg"
                '        .Height = 68
                '        .Width = 68
                '        '.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoFalse
                '        .LockAspectRatio = 0
                '    End With

                'Catch ex As Exception
                '    .LeftHeader = vbCr & vbCr & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                '    Debug.WriteLine("页眉图片" & ex.ToString())
                'End Try

            End With
            'excel.printpreview()
            'excel.PrintPreview()

            objExcel.Visible = True
            'objExcel.ActiveWindow.View = Excel.XlWindowView.xlPageBreakPreview
            objExcel.ActiveWindow.SelectedSheets.PrintPreview() '(显示打印预览, 未输出至excel)
            'excel.Workbooks(1).PrintOut()
            'excel.DisplayAlerts = False
            'excel.Quit()
        Catch ex As Exception
            Debug.WriteLine("打印错误" & ex.ToString())
            msg.Show(ex.Message)
        Finally
            Try
                If objExcel.ActiveWindow.View = Excel.XlWindowView.xlNormalView Then '分页预览
                    'objExcel.ActiveSheet.Unprotect(pwd)
                    wb.Close(False, False)
                    objExcel.Workbooks.Close()
                    objExcel.DisplayAlerts = False
                    objExcel.Quit()
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wb)
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel)
                    wb = Nothing
                    objExcel = Nothing
                    GC.Collect()
                End If
            Catch ex As Exception
                Debug.WriteLine(ex.ToString())
            End Try

        End Try
    End Sub

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Me.Cursor = Cursors.WaitCursor
        sender.Enabled = False
        Print()
        sender.Enabled = True
        Me.Cursor = Cursors.Default
    End Sub


    Private Sub cboSecond_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.btnPrint.Enabled = False
        Me.btnExport.Enabled = False
        Me.btnPDFExport.Enabled = False
        ' Me.BtnLimit.Enabled = False
    End Sub

    'Private Sub nudHour_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Me.btnPrint.Enabled = False
    'End Sub

    'Private Sub nudMinute_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    Me.btnPrint.Enabled = False
    'End Sub

    Private Sub dtpFrom_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpFrom.ValueChanged
        Me.btnPrint.Enabled = False
        Me.btnExport.Enabled = False
        Me.btnPDFExport.Enabled = False
        ' Me.BtnLimit.Enabled = False
    End Sub

    Private Sub dtpTo_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpTo.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Dim selectValues As New List(Of DataGridViewCell)
    Private Sub DataGridView2_CellMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView2.CellMouseClick
        If e.RowIndex < 0 Then Return
        If e.ColumnIndex < 1 Then Return 'skip first column

        Dim tmpObj As Object
        Dim value As Object

        value = Me.DataGridView2.Item(e.ColumnIndex, e.RowIndex).Value.ToString


        'Me.DataGridView1.MultiSelect = False
        'For Each c As DataGridViewCell In Me.DataGridView1.SelectedCells
        '    c.Selected = False
        'Next
        'If selectValues.Count > 0 Then '有上次查询记录

        'If selectValues(0).ColumnIndex = e.ColumnIndex And selectValues(0).Value.ToString Is value Then '是选择的值
        '    selectValues(0).Selected = True
        '    selectValues.RemoveAt(0)
        'Else
        selectValues.Clear() '清空上次列表, 重新加载新查询记录

        For Each r As DataGridViewRow In Me.DataGridView1.Rows
            tmpObj = r.Cells(e.ColumnIndex).Value
            If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Continue For
            If tmpObj.ToString = "未激活" Then
                Continue For
            Else

                If tmpObj.ToString = value Then
                    selectValues.Add(r.Cells(e.ColumnIndex))
                End If
            End If
        Next

        If selectValues.Count > 0 Then
            selectValues(0).Selected = True
            selectValues.RemoveAt(0)
        End If
        'End If

        'Else '无上次查询记录, 添加新查询记录

        '    For Each r As DataGridViewRow In Me.DataGridView1.Rows
        '        tmpObj = r.Cells(e.ColumnIndex).Value
        '        If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Continue For
        '        If tmpObj.ToString = "未激活" Then
        '            Continue For
        '        Else

        '            If tmpObj.ToString = value Then
        '                selectValues.Add(r.Cells(e.ColumnIndex))
        '                'r.Cells(e.ColumnIndex).Selected = True
        '            End If

        '        End If

        '    Next

        '    If selectValues.Count > 0 Then
        '        selectValues(0).Selected = True
        '        selectValues.RemoveAt(0)
        '    End If

        'End If

    End Sub

    Private Sub DataGridView1_CellMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
        If e.RowIndex < 0 Then Return
        If e.ColumnIndex < 1 Then Return '跳过时间列

        Dim tmpObj As Object = Me.DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value.ToString
        If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Return

        If tmpObj.ToString = "未激活" Then
            Exit Sub

        End If
        Dim value As Object = tmpObj

        Select Case Me.DataGridView1.Columns(e.ColumnIndex).Name
            Case "hTMax", "hTMin", "hTAvg"
                For Each col As String In tArray
                    tmpObj = Me.DataGridView1.Rows(e.RowIndex).Cells(col).Value
                    If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Continue For
                    If tmpObj.ToString = "未激活" Then
                        Exit Sub
                    Else
                        If tmpObj.ToString = value Then
                            Me.DataGridView1.Rows(e.RowIndex).Cells(col).Selected = True
                        End If

                    End If

                Next
            Case "hHMax", "hHMin", "hHAvg"
                For Each col As String In hArray
                    tmpObj = Me.DataGridView1.Rows(e.RowIndex).Cells(col).Value
                    If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Continue For
                    If tmpObj.ToString = "未激活" Then
                        Exit Sub
                    Else
                        If tmpObj.ToString = value Then
                            Me.DataGridView1.Rows(e.RowIndex).Cells(col).Selected = True
                        End If
                    End If
                Next
        End Select
    End Sub

    Private Sub cboRef_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboRef.SelectedIndexChanged
        Me.btnPrint.Enabled = False
        Me.btnExport.Enabled = False
        Me.btnPDFExport.Enabled = False
        ' Me.BtnLimit.Enabled = False

        If cboRef.SelectedIndex <> -1 Then
            btnRefresh.Enabled = True
            Me.BtnLimit.Enabled = True
        End If
    End Sub

    Private Sub bwSearch_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwSearch.DoWork
        Dim cbo_rti As RefTypeItem = e.Argument(0)
        Dim ret As Object
        e.Result = New Object() {True, Nothing}

        Dim str As String = String.Format("正在查询{0}历史数据……", cbo_rti)
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf SetSearchState), str)
        Else
            SetSearchState(str)
        End If

        ret = RefreshData(cbo_rti)

        If Me.InvokeRequired Then
            e.Result(0) = Me.Invoke(New BoolMethodHandler(AddressOf AddDataToGridView), ret)
        Else
            e.Result(0) = AddDataToGridView(ret)
        End If

        e.Result(1) = bwSearch.CancellationPending
    End Sub

    Private Sub bwSearch_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwSearch.ProgressChanged
        pbSearch.Value = e.ProgressPercentage
    End Sub

    Private Delegate Sub VoidMethodHandler(ByVal obj As Object)
    Private Delegate Function BoolMethodHandler(ByVal obj As Object) As Boolean
    Private Sub bwSearch_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwSearch.RunWorkerCompleted
        Me.pnlSearch.Visible = False

        If e.Result(0) Then
            Me.btnPrint.Enabled = True
            Me.btnExport.Enabled = True
            Me.btnPDFExport.Enabled = True
            '  Me.BtnLimit.Enabled = True
        ElseIf Not e.Result(1) Then '过滤取消操作
            'Me.DataGridView1.Columns.Clear()
            'Me.DataGridView2.Columns.Clear()
            Me.btnPrint.Enabled = False
            Me.btnExport.Enabled = False
            Me.btnPDFExport.Enabled = False
            '  Me.BtnLimit.Enabled = False
            msg.Show("指定时间范围没有数据,请重新设置时间范围")
        End If

        Me.cboRef.Enabled = True
        Me.dtpFrom.Enabled = True
        Me.dtpTo.Enabled = True
        Me.btnRefresh.Enabled = True
        Me.BtnLimit.Enabled = True
        Me.btnRefresh.Text = "查询"
        'Me.DataGridView1.Cursor = Cursors.Default
        GC.Collect()

        If e.Result(1) Then
            msg.Show("操作已取消")
        End If
    End Sub
    Private Sub SetDataGridViewColumnVisible(ByVal flag As Boolean)
        For i As Integer = 0 To DataGridView1.Columns.Count - 1
            Me.DataGridView1.Columns(i).Visible = flag
        Next
        For i As Integer = 0 To DataGridView2.Columns.Count - 1
            Me.DataGridView2.Columns(i).Visible = flag
        Next
    End Sub
    Private Sub AddDataGridViewColumns(ByVal obj As Object)
        Dim m_index As Integer
        Dim _GridViewColumnVisable As Boolean = True
        Dim apts As AiPortTypeService = New AiPortTypeService(Me.cboRef.SelectedItem)

        m_index = Me.DataGridView2.Columns.Add("vRowHead", String.Empty)
        Me.DataGridView2.Columns(m_index).Width = 50
        Me.DataGridView2.Columns(m_index).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        Me.DataGridView2.Columns(m_index).DefaultCellStyle.BackColor = System.Drawing.SystemColors.Control
        Me.DataGridView2.Columns(m_index).Frozen = True
        Me.DataGridView2.Columns(m_index).Visible = _GridViewColumnVisable
        Me.DataGridView2.Rows.Add(3)
        Me.DataGridView2.Rows(0).Cells(0).Value = "最大"
        Me.DataGridView2.Rows(1).Cells(0).Value = "最小"
        Me.DataGridView2.Rows(2).Cells(0).Value = "平均"

        '添加时间列标题
        m_index = Me.DataGridView1.Columns.Add("hDate", "时间")
        Me.DataGridView1.Columns(m_index).DataPropertyName = "hDate"
        Me.DataGridView1.Columns(m_index).Width = 140
        Me.DataGridView1.Columns(m_index).Frozen = True
        Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable
        Me.DataGridView1.Columns(m_index).DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss"




        '添加AI列标题
        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                Dim columnName As String = "AI" & Trim(apti.PortNo.ToString)

                m_index = Me.DataGridView1.Columns.Add(columnName, apti.PortName)
                Me.DataGridView1.Columns(m_index).DataPropertyName = columnName
                Me.DataGridView1.Columns(m_index).SortMode = DataGridViewColumnSortMode.NotSortable '2008.10.31
                Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable
                m_index = Me.DataGridView2.Columns.Add(columnName, apti.PortName) '添加统计列
                Me.DataGridView2.Columns(m_index).Visible = _GridViewColumnVisable
                'Me.DataGridView2.Columns(m_index).DefaultCellStyle.BackColor = Color.LightGray
            End If
        Next

        '添加温度min/max/avg列标题
        If tArray.Count > 0 Then
            m_index = Me.DataGridView1.Columns.Add("hTMax", "最大温度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hTMax"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = System.Drawing.Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            m_index = Me.DataGridView1.Columns.Add("hTMin", "最小温度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hTMin"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = System.Drawing.Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            m_index = Me.DataGridView1.Columns.Add("hTAvg", "平均温度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hTAvg"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = System.Drawing.Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            '去处统计中T的3列; 2008.10.31
            'Me.DataGridView2.Columns.Add("hTMax", "Tmax") '添加统计列
            'Me.DataGridView2.Columns.Add("hTMin", "Tmin")
            'Me.DataGridView2.Columns.Add("hTAvg", "Tavg")
        End If

        '添加湿度min/max/avg列标题
        If hArray.Count > 0 Then
            m_index = Me.DataGridView1.Columns.Add("hHMax", "最大湿度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hHMax"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = System.Drawing.Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            m_index = Me.DataGridView1.Columns.Add("hHMin", "最小湿度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hHMin"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = System.Drawing.Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            m_index = Me.DataGridView1.Columns.Add("hHAvg", "平均湿度")
            Me.DataGridView1.Columns(m_index).DataPropertyName = "hHAvg"
            Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = System.Drawing.Color.LightGray
            Me.DataGridView1.Columns(m_index).Visible = _GridViewColumnVisable

            '去处统计中H的3列; 2008.10.31
            'Me.DataGridView2.Columns.Add("hHMax", "Hmax") '添加统计列
            'Me.DataGridView2.Columns.Add("hHMin", "Hmin")
            'Me.DataGridView2.Columns.Add("hHAvg", "Havg")
        End If

    End Sub
    Private Sub DataGridView1BindSource(ByVal obj As Object)
        Dim ret = obj
        Dim ds As DataSet = ret(0)
        Dim vMax = ret(1)
        Dim vMin = ret(2)
        Dim vAvg = ret(3)
        Dim vLen = ret(4)

        '绑定DataSet
        Me.DataGridView1.DataSource = ds.Tables(0)


        '取消统计表排序
        For i As Integer = 0 To Me.DataGridView2.Columns.Count - 1
            Me.DataGridView2.Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable
        Next

        If ds.Tables(0).Rows.Count > 0 Then
            '添加统计信息
            For i As Integer = 0 To vLen - 1
                Me.DataGridView2.Rows(0).Cells(i + 1).Value = vMax(i) 'i + 1跳过第一列
                Me.DataGridView2.Rows(1).Cells(i + 1).Value = vMin(i)
                'Me.DataGridView2.Rows(2).Cells(i + 1).Value = Math.Round(vAvg(i), 2)
                If vMax(i) Is "--" Then
                    Me.DataGridView2.Rows(2).Cells(i + 1).Value = vAvg(i)
                Else
                    Me.DataGridView2.Rows(2).Cells(i + 1).Value = Format(vAvg(i), "0.0")

                End If

            Next
        End If
    End Sub
    Private Sub SetSearchState(ByVal obj As Object)
        Me.lblSearchState.Text = obj
    End Sub
    Private Function AddDataToGridView(ByVal obj As Object) As Boolean
        If obj IsNot Nothing Then
            AddDataGridViewColumns(Nothing)
            DataGridView1BindSource(obj)
        Else
            Return False
        End If

        Return True
    End Function
    Private Sub ReportProgress(ByVal value As Integer)
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf ReportProgressMethod), value)
        Else
            ReportProgressMethod(value)
        End If
    End Sub
    Private Sub ReportProgressMethod(ByVal obj As Object)
        Me.bwSearch.ReportProgress(obj)
    End Sub

    Private Sub HDDocViewForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        DisposeBackWorker()
    End Sub
    Private Sub DisposeBackWorker()
        If Me.bwSearch IsNot Nothing Then
            Me.bwSearch.CancelAsync()
            Me.bwSearch.Dispose() : Me.bwSearch = Nothing
        End If
        GC.Collect()
    End Sub

    Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
        Me.Cursor = Cursors.WaitCursor
        sender.Enabled = False
        PrintExport()
        sender.Enabled = True
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub PrintExport()
        ' Dim k As Integer
        Dim dt As DataTable
        dt = CType(Me.DataGridView1.DataSource, DataTable)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            msg.Show("没有数据")
            Exit Sub
        End If


        For i As Integer = 0 To dt.Rows.Count - 1
            Dim r As DataRow = dt.Rows(i)
            If r(2).ToString = "未激活" Then
                r.Delete()
                Continue For
            End If
        Next

        dt.AcceptChanges()

        Dim objExcel As New Excel.Application

        Dim wb As Excel.Workbook = objExcel.Workbooks.Add()

        '  excel.Application.Workbooks.Add(True)
        'objExcel.Visible = True

        ReDim Preserve cols(100)


        Dim index As Integer = 0
        cols(index) = "序号"
        headers(index) = "序号"
        For i As Integer = 0 To Me.DataGridView1.Columns.Count - 1
            'For i As Integer = 0 To dt.Rows.Count - 1




            If Me.DataGridView1.Columns(i).Visible Then
                index += 1
                cols(index) = Me.DataGridView1.Columns(i).DataPropertyName
                headers(index) = Me.DataGridView1.Columns(i).HeaderText
            End If
        Next

        ReDim Preserve cols(index)

        'Dim bRow As Integer = dt.Rows.Count
        ''Dim values(,) As Object
        Dim values(dt.Rows.Count, cols.Length + 1) As Object 'cols.Length + 1:时间为2列
        'If bRow Mod 32 <> 0 Then
        '    Dim ba As Integer = bRow \ 32
        '    bRow = (ba + 1) * 32
        '    'ReDim values(bRow, cols.Length)
        'Else
        '    'ReDim values(bRow, cols.Length)
        'End If
        'For i As Integer = 0 To values.GetLength(0) - 1
        '    For j As Integer = 0 To values.GetLength(1) - 1
        '        values(i, j) = Strings.Space(1)
        '    Next
        'Next

        For j As Integer = 0 To cols.Length
            If j > 1 Then
                values(0, j + 1) = headers(j) 'j+1:跳过时间2列(共2列)
            Else
                values(0, j) = headers(j)
            End If
        Next

        '
        For i As Integer = 0 To dt.Rows.Count - 1
            Dim r As DataRow = dt.Rows(i)
            'If r(2) = "未激活" Then
            '    ' r.Delete()
            '    Continue For
            'End If

            values(i + 1, 0) = i + 1
            For j As Integer = 1 To cols.Length - 1 '跳过GridView第一列


                If j > 1 Then
                    values(i + 1, j + 1) = r(cols(j)) 'j+1:跳过时间2列(共2列)
                Else
                    values(i + 1, j) = r(cols(j))
                End If
            Next
        Next

        'Get stat values
        Dim statValues(3, Me.DataGridView1.Columns.Count) As Object
        For i As Integer = 0 To statValues.GetLength(0) - 1 'init values
            For j As Integer = 0 To statValues.GetLength(1) - 1
                'If statValues(i, j) = "未激活" Then
                '    Continue For
                'Else
                statValues(i, j) = String.Empty

                ' End If

            Next
        Next
        For i As Integer = 0 To Me.DataGridView2.Rows.Count - 1 '3
            Dim r As DataGridViewRow = Me.DataGridView2.Rows(i)
            For j As Integer = 0 To Me.DataGridView2.Columns.Count - 1

                statValues(i, j) = r.Cells(j).Value



            Next j
        Next i

        Dim pwd As String = System.Guid.NewGuid().ToString()
        Try
            'objExcel.Visible = True
            'objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, cols.Length)).Value = values
            'objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(bRow, cols.Length)).Value = values

            '设置格式
            objExcel.Columns("A:AA").Select()
            objExcel.Selection.HorizontalAlignment = Excel.Constants.xlCenter
            objExcel.Selection.Font.Size = 10
            objExcel.Selection.ColumnWidth = 10

            '序号
            objExcel.Range("A1", "A" & (dt.Rows.Count + 1)).ColumnWidth = 5
            'objExcel.Range("A1", "A" & (dt.Rows.Count + 1)).RowHeight = 20

            '监控时间
            'objExcel.Range("B1", objExcel.Cells(dt.Rows.Count + 1, 2)).Insert(Excel.XlInsertShiftDirection.xlShiftToRight) '插入合并列
            objExcel.Range("B1", objExcel.Cells(dt.Rows.Count + 1, 3)).ColumnWidth = 9
            objExcel.Range("B1", objExcel.Cells(dt.Rows.Count + 1, 3)).NumberFormatLocal = "yyyy-mm-dd hh:mm:ss"

            Dim totalIndex As Integer = 4 + tArray.Count + hArray.Count
            '设置温湿度列宽; 2008.10.31
            objExcel.Range(objExcel.Cells(1, 4), objExcel.Cells(dt.Rows.Count + 1, totalIndex)).ColumnWidth = 6
            objExcel.Range(objExcel.Cells(1, 4), objExcel.Cells(dt.Rows.Count + 1, totalIndex)).NumberFormatLocal = "0.00"

            '设置温湿度统计列宽; 2008.10.31
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Rows.Count + 1, 26)).ColumnWidth = 8
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Rows.Count + 1, 26)).NumberFormatLocal = "0.00"
            objExcel.Range(objExcel.Cells(1, totalIndex), objExcel.Cells(dt.Rows.Count + 1, totalIndex - 1 + IIf(tArray.Count > 0, 3, 0) + IIf(hArray.Count > 0, 3, 0))).Interior.Color = RGB(255, 221, 221) 'array.count > 0

            'Dim pageRow As Integer = 27 '不包括统计的3行; 2008.10.31
            Dim statRow As Integer = 3
            Dim totalCount As Integer = Math.Ceiling(dt.Rows.Count / 30) * 30 - statRow
            If totalCount < dt.Rows.Count Then
                totalCount += statRow
            End If
            '合并单元格
            Dim range As Excel.Range
            range = objExcel.Range(objExcel.Cells(1, 2), objExcel.Cells(totalCount + 1, 3)) '合并日期单元格(dt.Rows.Count); 2008.10.31
            range.Merge(True)
            'For i As Integer = 1 To totalCount + 1
            '    range = objExcel.Range(objExcel.Cells(1, 2), objExcel.Cells(totalCount + 1, 3))
            '    range.Merge(True)
            'Next
            '合并统计单元格
            range = objExcel.Range(objExcel.Cells(totalCount + 2, 1), objExcel.Cells(totalCount + 4, 2)) '2008.10.31
            'range = objExcel.Range(objExcel.Cells(bRow - 2, 1), objExcel.Cells(bRow, 2))
            range.Merge()
            range.Value2 = "统计"
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
            range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
            range.Font.Size = 20

            'cols.Length + 1:时间为2列
            objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, cols.Length + 1)).Value2 = values

            '添加统计信息
            Dim statRange As Excel.Range
            statRange = objExcel.Range(objExcel.Cells(totalCount + 2, 3), objExcel.Cells(totalCount + 4, cols.Length + 1)) '2008.10.31
            'statRange = objExcel.Range(objExcel.Cells(bRow - 2, 3), objExcel.Cells(bRow, cols.Length + 1))
            statRange.Value2 = statValues
            'statRange.Interior.Color = RGB(221, 221, 221)
            'statRange.Interior.Pattern = 4
            'objExcel.Cells(dt.Rows.Count + 2, 1).Interior.Color = RGB(221, 221, 221)
            'objExcel.Cells(dt.Rows.Count + 2, 1).Interior.Pattern = 4

            '设置边框
            range = objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(totalCount + 4, cols.Length + 1))
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlContinuous

            '设置保护
            'Try
            '    objExcel.ActiveSheet.Protect(pwd, _
            '                AllowFormattingCells:=False, _
            '                AllowFormattingColumns:=False, _
            '                AllowFormattingRows:=False, _
            '                AllowInsertingColumns:=False, _
            '                AllowInsertingRows:=False, _
            '                AllowInsertingHyperlinks:=False, _
            '                AllowDeletingColumns:=False, _
            '                AllowDeletingRows:=False _
            '    )
            'Catch ex As Exception
            '    objExcel.ActiveSheet.Protect(pwd)
            'End Try

            '温湿度值
            'Dim ws As Excel.Worksheet = objExcel.ActiveSheet
            'With ws.PageSetup
            '    '.LeftHeader = "&G" & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
            '    .LeftHeader = vbCr & vbCr & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
            '    .CenterHeader = String.Format("&""宋体,加粗""&28 {0}温/湿度查询 ", Me.cboRef.Text)
            '    .RightHeader = vbCr & vbCr & vbCr & "共&N页 第&P页"
            '    .LeftFooter = "养护员："
            '    .CenterFooter = ""
            '    .RightFooter = "打印日期：&D &T"
            '    .LeftMargin = objExcel.Application.InchesToPoints(0.6)
            '    .RightMargin = objExcel.Application.InchesToPoints(0.4)
            '    .TopMargin = objExcel.Application.InchesToPoints(1.08)
            '    .BottomMargin = objExcel.Application.InchesToPoints(0.68)
            '    .HeaderMargin = objExcel.Application.InchesToPoints(0.22)
            '    .FooterMargin = objExcel.Application.InchesToPoints(0.5)
            '    .PrintHeadings = False
            '    .PrintGridlines = True
            '    '.PrintComments = objExcel.xlPrintNoComments
            '    ''.PrintQuality = 300
            '    .CenterHorizontally = False
            '    .CenterVertically = False
            '    '.Orientation = objExcel.xlPortrait
            '    .Draft = False
            '    '.PaperSize = Excel.XlPaperSize.xlPaperA4
            '    .Orientation = Excel.XlPageOrientation.xlLandscape '横向打印
            '    '.FirstPageNumber = objExcel.xlAutomatic
            '    '.Order = objExcel.xlDownThenOver
            '    '.BlackAndWhite = False
            '    .Zoom = 100
            '    '.PrintErrors = objExcel.xlPrintErrorsDisplayed

            '    '.PrintArea = "A1:U" & bRow
            '    .FitToPagesWide = 1
            '    .FitToPagesTall = 1
            '    .PrintTitleRows = "$1:$1"




            'End With


            objExcel.Visible = True

        Catch ex As Exception
            Debug.WriteLine("打印错误" & ex.ToString())
            msg.Show(ex.Message)
        Finally


        End Try
    End Sub

    Private Sub Btn_pSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_pSet.Click
        Dim frm As New DocViewSetForm
        ' frm.ShowDialog()
        If frm.ShowDialog = Windows.Forms.DialogResult.OK Then
            GetSpace()

        End If
    End Sub

    Private Sub BtnLimit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLimit.Click
        Dim frm As New TempAndHumLimite(cboRef.SelectedItem)
        frm.ShowDialog()

        If frm.StringChange Then
            _LimitStr = "and " + frm.LimitItem

        End If

    End Sub

    Private Sub btnPDFExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPDFExport.Click
   
        Try

            Dim frm As New SaveFileDialog()
            frm.Filter = "PDF文件(*.pdf)|*.pdf"
            frm.FileName = ""
            If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then



                ConvertGridViewToPdf(frm.FileName, "C:\WINDOWS\Fonts\SIMHEI.TTF", 6)   'DataGridView1,

                msg.Show("文件导出成功")

                ' frm.OpenFile()
                System.Diagnostics.Process.Start(frm.FileName)

            End If




        Catch ex As Exception
            Debug.Write(ex)

        End Try

    End Sub
    Public Sub ConvertGridViewToPdf(ByVal filename As String, ByVal FontPath As String, ByVal FontSize As Single)

        DataGridView1.AllowDrop = False
        Dim countColumns As Integer = Me.DataGridView1.Columns.Count - 1
        Dim count2 As Integer = Me.DataGridView2.Columns.Count
        Dim a As Document

        If countColumns > 17 Then
            a = New Document(PageSize.A4.Rotate(), 50, 50, 50, 50)  '横版
        Else
            a = New Document(PageSize.A4, 25, 25, 25, 25)  '竖版

        End If


        ' 
        Dim strFileName As String = filename

        Dim writer As PdfWriter = PdfWriter.GetInstance(a, New FileStream(strFileName, FileMode.Create))


        Try

            '创建PDF文档中的字体
            Dim baseFont As BaseFont
            baseFont = pdf.BaseFont.CreateFont(FontPath, baseFont.IDENTITY_H, baseFont.NOT_EMBEDDED)
            '根据字体路径和字体大小属性创建字体
            Dim font As Font = New Font(baseFont, FontSize)

            Dim footer As HeaderFooter = New HeaderFooter(New Phrase("-- ", font), New Phrase(" --", font))
            footer.Border = Rectangle.NO_BORDER ';        // 不显示两条横线
            footer.Alignment = Rectangle.ALIGN_CENTER ';  // 让页码居中
            a.Footer = footer ';
            '//打开目标文档对象
            a.Open()


            '//标题居中
            Dim aparagraph As Paragraph = New Paragraph(String.Format(" {0}温/湿度数据 ", Me.cboRef.Text), New Font(baseFont, 20))
            aparagraph.Alignment = Element.ALIGN_CENTER
            a.Add(aparagraph)


            aparagraph = New Paragraph(vbCr & String.Format("监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr, New Font(baseFont, 9))

            aparagraph.Alignment = Element.ALIGN_LEFT
            a.Add(aparagraph)
            '//根据数据表内容创建一个PDF格式的表
            Dim pdfTable As PdfPTable = New PdfPTable(countColumns + 1)
            Dim pdftable1 As PdfPTable = New PdfPTable(count2)
            pdftable1.DefaultCell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY

            Dim tablewidths1(count2 - 1) As Single

            For k As Integer = 0 To tablewidths1.Length - 1
                tablewidths1(k) = 20

            Next

            pdftable1.TotalWidth = a.Right - a.Left

            pdftable1.SetWidths(tablewidths1)
            pdftable1.LockedWidth = True



            pdfTable.DefaultCell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY ';
            Dim tablewidths(countColumns) As Single

            For k As Integer = 0 To tablewidths.Length - 1
                If k = 0 Then
                    tablewidths(k) = 30
                Else
                    tablewidths(k) = 15

                End If
            Next
            pdfTable.TotalWidth = a.Right - a.Left

            pdfTable.SetWidths(tablewidths)
            pdfTable.LockedWidth = True

            ' Dim aPhrase As Phrase

            ' pdftable.Chunks.
            '// 添加表头
            For j As Integer = 0 To countColumns
                If Me.DataGridView1.Columns(j).Visible Then

                    'aparagraph = New Phrase(Me.DataGridView1.Columns(j).HeaderText, font)
                    'aparagraph.Alignment = Element.ALIGN_CENTER
                    'pdfTable.AddCell(aparagraph)

                    'aPhrase = New Phrase(Me.DataGridView1.Columns(j).HeaderText
                    'aPhrase.a()
                    pdfTable.AddCell(New Phrase(Me.DataGridView1.Columns(j).HeaderText, font))

                End If


            Next

            ' // 告诉程序这行是表头，这样页数大于1时程序会自动为你加上表头。
            pdfTable.HeaderRows = 1


            '// 添加数据
            '// 设置表体背景色
            pdfTable.DefaultCell.BackgroundColor = Color.WHITE
            ' pdfTable.SetTotalWidth(200)

            For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1 '3
                Dim r As DataGridViewRow = Me.DataGridView1.Rows(i)
                For j As Integer = 0 To Me.DataGridView1.Columns.Count - 1

                    pdfTable.AddCell(New Phrase(r.Cells(j).Value.ToString, font))



                Next j
            Next i

            '//在目标文档中添加转化后的表数据
            a.Add(pdfTable)


            aparagraph = New Paragraph(vbCr & vbCr, New Font(baseFont, 9))

            aparagraph.Alignment = Element.ALIGN_LEFT
            a.Add(aparagraph)

            For j As Integer = 0 To count2 - 1
                If j = 0 Then
                    pdftable1.AddCell(New Phrase("", font))
                Else

                    If Me.DataGridView2.Columns(j).Visible Then

                        pdftable1.AddCell(New Phrase(Me.DataGridView2.Columns(j).HeaderText, font))

                    End If

                End If



            Next
            pdftable1.HeaderRows = 1

            pdftable1.DefaultCell.BackgroundColor = Color.WHITE

            For i As Integer = 0 To Me.DataGridView2.Rows.Count - 1 '3
                Dim r As DataGridViewRow = Me.DataGridView2.Rows(i)
                For j As Integer = 0 To Me.DataGridView2.Columns.Count - 1

                    pdftable1.AddCell(New Phrase(r.Cells(j).Value.ToString, font))



                Next j
            Next i

            '//在目标文档中添加转化后的表数据
            a.Add(pdftable1)



        Catch ex As Exception

        Finally

            a.Close()
            writer.Close()

            ' a.Open()

        End Try

    End Sub
End Class

